package com.wrox.todolist;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

public class TodoContentProvider extends ContentProvider {
	public static final Uri CONTENT_URI =
			Uri.parse("content://com.wrox.todoprovider/todoitems/");
	public static final String KEY_ID = "_id";
	public static final String KEY_TASK = "task";
	public static final String KEY_CREATED = "creation_date";
	public static final String KEY_FINISHED = "finished";
	
	private Helper helper;
	private static final UriMatcher matcher;
	private static final int ALLROWS = 1;
	private static final int SINGLE_ROW = 0;
	static {
		matcher = new UriMatcher(UriMatcher.NO_MATCH);
		matcher.addURI("com.wrox.todoprovider", "todoitems", ALLROWS);
		matcher.addURI("com.wrox.todoprovider", "todoitems/#", SINGLE_ROW);
	}
	
	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		SQLiteDatabase db = helper.getWritableDatabase();
		switch (matcher.match(uri)) {
		case SINGLE_ROW:
			String rowID = uri.getPathSegments().get(1);
			selection = KEY_ID + " = " + rowID +
					(!TextUtils.isEmpty(selection) ? " AND (" + selection + ")" : "");
		default:
			break;
		}
		if (selection == null) selection = "1";
		int deleteCount = db.delete(Helper.DATABASE_TABLE, selection, selectionArgs);
		getContext().getContentResolver().notifyChange(uri, null);
		return deleteCount;
	}

	@Override
	public String getType(Uri uri) {
		switch (matcher.match(uri)) {
		case ALLROWS:
			return "vnd.android.cursor.dir/vnd.wrox.todos";
		case SINGLE_ROW:
			return "vnd.android.cursor.item/vnd.wrox.todos";
		default:
			throw new IllegalArgumentException("Unsupported Uri: " + uri);
		}
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		SQLiteDatabase db = helper.getWritableDatabase();
		String nullColumnHack = null;
		long id = db.insert(Helper.DATABASE_TABLE, nullColumnHack, values);
		if (id > -1) {
			Uri insertedId = ContentUris.withAppendedId(CONTENT_URI, id);
			getContext().getContentResolver().notifyChange(uri, null);
			return insertedId;
		}
		return null;
	}

	@Override
	public boolean onCreate() {
		helper = new Helper(getContext(), Helper.DATABASE_NAME, null, Helper.DATABASE_VERSION);
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		SQLiteDatabase db = helper.getWritableDatabase();
		String groupBy = null;
		String having = null;
		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
		qb.setTables(Helper.DATABASE_TABLE);
		switch (matcher.match(uri)) {
		case SINGLE_ROW:
			String rowID = uri.getPathSegments().get(1);
			qb.appendWhere(KEY_ID + " = " + rowID);
		default:
			break;
		}
		return qb.query(db, projection, selection, selectionArgs, groupBy, having, sortOrder);
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		SQLiteDatabase db = helper.getWritableDatabase();
		switch (matcher.match(uri)) {
		case SINGLE_ROW:
			String rowID = uri.getPathSegments().get(1);
			selection = KEY_ID + " = " + rowID +
					(!TextUtils.isEmpty(selection) ? " AND (" + selection + ")" : "");
		default:
			break;
		}
		int updateCount = db.update(Helper.DATABASE_TABLE, values, selection, selectionArgs);
		getContext().getContentResolver().notifyChange(uri, null);
		return updateCount;
	}

	private static class Helper extends SQLiteOpenHelper {
		public static final String DATABASE_NAME = "todoDatabase.db";
		public static final int    DATABASE_VERSION = 1;
		public static final String DATABASE_TABLE = "todoItemTable";
		
		private static final String DATABASE_CREATE = "create table " +
				DATABASE_TABLE + " (" + 
				KEY_ID + " integer primary key autoincrement, " +
				KEY_TASK + " text not null, " + 
				KEY_CREATED + " long," +
				KEY_FINISHED + " integer not null);";
		
		public Helper(Context context, String name, CursorFactory factory,
				int version) {
			super(context, name, factory, version);
			// TODO Auto-generated constructor stub
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(DATABASE_CREATE);
			
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w("TodoDB", "Upgrading from version " + oldVersion
					+ " to " + newVersion + ", which will destroy all old data");
			db.execSQL("drop table if it exists " + DATABASE_TABLE);
			onCreate(db);
		}
		
	}
}
